<script>
import { GlCard, GlSkeletonLoader } from '@gitlab/ui';
import SeverityBadge from 'ee/vue_shared/security_reports/components/severity_badge.vue';
import { DASHBOARD_TYPES } from 'ee/security_dashboard/store/constants';
import { createAlert } from '~/alert';
import { s__ } from '~/locale';
import countsQuery from 'ee/security_dashboard/graphql/queries/vulnerability_severities_count.query.graphql';
import { SEVERITIES } from '~/vulnerabilities/constants';

export default {
  components: { GlCard, GlSkeletonLoader, SeverityBadge },
  inject: ['fullPath', 'dashboardType'],
  props: {
    filters: {
      type: Object,
      required: false,
      default: null,
    },
  },
  data() {
    return {
      counts: {},
    };
  },
  apollo: {
    counts: {
      query: countsQuery,
      errorPolicy: 'none',
      variables() {
        return {
          fullPath: this.fullPath,
          isProject: this.dashboardType === DASHBOARD_TYPES.PROJECT,
          isGroup: this.dashboardType === DASHBOARD_TYPES.GROUP,
          isInstance: this.dashboardType === DASHBOARD_TYPES.INSTANCE,
          ...this.filters,
        };
      },
      update(data) {
        return data[this.dashboardType].vulnerabilitySeveritiesCount;
      },
      error() {
        createAlert({
          message: s__(
            'SecurityReports|Error fetching the vulnerability counts. Please check your network connection and try again.',
          ),
        });
      },
      skip() {
        return !this.filters;
      },
    },
  },
  computed: {
    isLoadingCounts() {
      return !this.filters || this.$apollo.queries.counts.loading;
    },
    severityCounts() {
      return SEVERITIES.map((severity) => ({
        severity,
        count: this.counts[severity] || 0,
      }));
    },
  },
  watch: {
    severityCounts() {
      this.$emit('counts-changed', this.severityCounts);
    },
  },
};
</script>

<template>
  <div class="vulnerability-counts gl-font-weight-bold gl-text-center">
    <gl-card
      v-for="{ severity, count } in severityCounts"
      :key="severity"
      :data-testid="severity"
      header-class="gl-p-3"
      body-class="gl--flex-center"
    >
      <template #header>
        <severity-badge :severity="severity" class="gl-text-center!" />
      </template>

      <template #default>
        <gl-skeleton-loader v-if="isLoadingCounts" :equal-width-lines="true" :lines="1" />
        <span v-else class="gl-font-size-h2">{{ count }}</span>
      </template>
    </gl-card>
  </div>
</template>
